import random

from django.shortcuts import render
from django.views import View
from django.http import JsonResponse, HttpResponse
from .libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from .constants import IMAGE_CODE_REDIS_EXPIRES, SMS_CODE_REDIS_EXPIRES, SEND_SMS_TEMPLATE_ID
from .libs.yuntongxun.ccp_sms import CCP
from celery_tasks.sms.tasks import send_sms_code


class ImageCodeView(View):
    def get(self, request, uuid):
        text, img = captcha.generate_captcha()
        redis_conn = get_redis_connection('verify_code')
        redis_conn.setex('img_%s' % uuid, IMAGE_CODE_REDIS_EXPIRES, text)

        return HttpResponse(img, content_type='image/jpg')


class SMSCodeView(View):
    def get(self, request, mobile):
        image_code_client = request.GET.get('image_code')
        uuid = request.GET.get('uuid')

        if not all([mobile, image_code_client, uuid]):
            return JsonResponse('error', safe=False)

        redis_conn = get_redis_connection('verify_code')
        image_code_server = redis_conn.get('img_%s' % uuid).decode()
        if image_code_server is None:
            return JsonResponse({'code': '4001', 'errmsg': '图形验证码已失效'})

        redis_conn.delete('img_%s' % uuid)
        if image_code_client.lower() != image_code_server.lower():
            return JsonResponse({'code': '', 'errmsg': ''})

        sms_code = '%06d' % random.randint(0, 999999)
        redis_conn.setex('sms_%s' % mobile, SMS_CODE_REDIS_EXPIRES, sms_code)

        # CCP().send_template_sms(mobile, [sms_code, SMS_CODE_REDIS_EXPIRES // 60], SEND_SMS_TEMPLATE_ID)
        send_sms_code.delay(mobile, sms_code)

        return JsonResponse({'code': '0', 'errmsg': '发送短信成功'})
